document.addEventListener('DOMContentLoaded', () => {
    const refreshBtn = document.getElementById('refreshBtn');
    const clearBtn = document.getElementById('clearBtn');
    const expandBtn = document.getElementById('expandBtn');
    const collapseBtn = document.getElementById('collapseBtn');
    const statusDiv = document.getElementById('status');
    const treeView = document.getElementById('treeView');
    const screenshotBtn = document.getElementById('screenshotBtn');
    const screenshotBtnNew = document.getElementById('screenshotBtnNew');
    const screenshotImg = document.getElementById('screenshotImg');

    const clickTreeBtn = document.getElementById('clickTreeBtn');
    const imagesTreeBtn = document.getElementById('imagesTreeBtn');
    const packageAndClassName = document.getElementById('packageAndClassName');
    const textTreeBtn = document.getElementById('textTreeBtn');
    const textTreeBtn1 = document.getElementById('textTreeBtn1');

    // 全局变量，存储当前所有节点元素

    let allNodes = [];
    let currentScreenshotUrl = '';

    refreshBtn.addEventListener('click', loadTreeData);
    clearBtn.addEventListener('click', clearTreeView);
    expandBtn.addEventListener('click', expandAllNodes);
    collapseBtn.addEventListener('click', collapseAllNodes);
    screenshotBtn.addEventListener('click', takeScreenshot);
    screenshotBtnNew.addEventListener('click', takeScreenshotNew);
    clickTreeBtn.addEventListener('click', clickTreeLoad);
    imagesTreeBtn.addEventListener('click', imagesTreeLoad);
    packageAndClassName.addEventListener('click', handlePackageAndClassName);
    textTreeBtn.addEventListener('click', textTreeLoad);
    textTreeBtn1.addEventListener('click', textTreeLoad1);

    function handlePackageAndClassName() {
            fetch('/getPackageNameAndClassName')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                   console.log(data)
                   if (data.error) {
                      throw new Error(data.error);
                  }
                  document.getElementById('packageName').innerHTML = data.packageName
                  document.getElementById('className').innerHTML = data.className
                  // 默认展开所有节点
                  expandAllNodes();
                  statusDiv.textContent = 'UI tree loaded successfully';
                  statusDiv.style.color = 'green';
                })
                .catch(error => {

                })
                .finally(() => {
                    showLoading(false);
                });
        }

    function clickTreeLoad() {
        fetch('/clickTree')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
               console.log(data)
               if (data.error) {
                  throw new Error(data.error);
              }
              renderTree1(data);
              // 默认展开所有节点
              expandAllNodes();
              statusDiv.textContent = 'UI tree loaded successfully';
              statusDiv.style.color = 'green';
            })
            .catch(error => {

            })
            .finally(() => {
                showLoading(false);
            });
    }

    function imagesTreeLoad() {
        fetch('/imagesTree')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
               console.log(data)
               if (data.error) {
                  throw new Error(data.error);
              }
              renderTree1(data);
              // 默认展开所有节点
              expandAllNodes();
              statusDiv.textContent = 'UI tree loaded successfully';
              statusDiv.style.color = 'green';
            })
            .catch(error => {

            })
            .finally(() => {
                showLoading(false);
            });
    }

    function textTreeLoad() {
        fetch('/textTree')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
               console.log(data)
               if (data.error) {
                   throw new Error(data.error);
               }
               renderTree1(data);
               // 默认展开所有节点
               expandAllNodes();
               statusDiv.textContent = 'UI tree loaded successfully';
               statusDiv.style.color = 'green';
            })
            .catch(error => {

            })
            .finally(() => {
                showLoading(false);
            });
    }

    function textTreeLoad1() {
            var txt = document.getElementById("inputText").value
            fetch('/nodeByText?text=' + txt)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                   console.log(data)
                   if (data.error) {
                       throw new Error(data.error);
                   }
                   renderTree1(data);
                   // 默认展开所有节点
                   expandAllNodes();
                   statusDiv.textContent = 'UI tree loaded successfully';
                   statusDiv.style.color = 'green';
                })
                .catch(error => {

                })
                .finally(() => {
                    showLoading(false);
                });
        }

    function loadTreeData() {
        showLoading(true);
        statusDiv.textContent = 'Loading UI tree...';
        statusDiv.style.color = '';

        fetch('/tree')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                renderTree(data);
                // 默认展开所有节点
                expandAllNodes();
                statusDiv.textContent = 'UI tree loaded successfully';
                statusDiv.style.color = 'green';
            })
            .catch(error => {
                console.error('Error fetching tree data:', error);
                statusDiv.textContent = `Error: ${error.message}`;
                statusDiv.style.color = 'red';
            })
            .finally(() => {
                showLoading(false);
            });
    }

    function expandAllNodes() {
        allNodes.forEach(node => {
            const header = node.querySelector('.node-header');
            const content = node.querySelector('.node-content');

            if (!header.classList.contains('expanded')) {
                header.classList.add('expanded');
                content.classList.add('visible');
            }
        });
    }

    function collapseAllNodes() {
        allNodes.forEach(node => {
            const header = node.querySelector('.node-header');
            const content = node.querySelector('.node-content');

            if (header.classList.contains('expanded')) {
                header.classList.remove('expanded');
                content.classList.remove('visible');
            }
        });
    }

    function renderTree(node) {
        treeView.innerHTML = '';
        allNodes = [];
        const rootElement = createNodeElement(node, 0);
        treeView.appendChild(rootElement);
    }

    function renderTree1(nodes) {
        treeView.innerHTML = '';
        allNodes = [];
        nodes.forEach((item, index) => {
            const rootElement = createNodeElement(item, 0);
            treeView.appendChild(rootElement);
        })
    }

    function createNodeElement(node, depth) {
        const nodeElement = document.createElement('div');
        nodeElement.className = 'node';

        // 存储节点元素引用
        allNodes.push(nodeElement);

        const header = document.createElement('div');
        header.className = 'node-header expanded'; // 默认添加expanded类

        // 节点标题
        const title = document.createElement('span');
        title.className = 'node-title';
        title.textContent = node.className || 'Unknown';
        header.appendChild(title);

        // 如果是图片节点，添加图标和截图按钮
        if (true) {
//            const imageIcon = document.createElement('span');
//            imageIcon.className = 'image-icon';
//            imageIcon.innerHTML = '🖼️';
//            header.insertBefore(imageIcon, title);

            const captureBtn = document.createElement('button');
            captureBtn.className = 'capture-btn';
            captureBtn.textContent = 'Capture';
            captureBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                captureSpecificNode(node.id, node.bounds);
            });
            header.appendChild(captureBtn);
        }

        const content = document.createElement('div');
        content.className = 'node-content visible'; // 默认添加visible类

        // 添加节点属性
        const properties = [
            `Text: ${node.text || 'N/A'}`,
            `Desc: ${node.desc || 'N/A'}`,
            `id: ${node.id || 'N/A'}`,
            `Bounds: [${node.bounds.left}, ${node.bounds.top}] - [${node.bounds.right}, ${node.bounds.bottom}]`,
            `Clickable: ${node.clickable ? 'Yes' : 'No'}`,
            `isVisibleToUser: ${node.isVisibleToUser ? 'Yes' : 'No'}`,
            `Long-clickable: ${node.longClickable ? 'Yes' : 'No'}`,
            `Scrollable: ${node.scrollable ? 'Yes' : 'No'}`,
            `Size: ${node.bounds.right - node.bounds.left} x ${node.bounds.bottom - node.bounds.top}`
        ];

        const infoContainer = document.createElement('div');
        infoContainer.className = 'node-info';

        properties.forEach(prop => {
            const propElement = document.createElement('span');
            propElement.className = 'info-item';
            propElement.textContent = prop;
            infoContainer.appendChild(propElement);
        });

        content.appendChild(infoContainer);

        // 添加子节点
        if (node.children && node.children.length > 0) {
            const childrenHeader = document.createElement('h4');
            childrenHeader.textContent = `Children (${node.children.length})`;
            content.appendChild(childrenHeader);

            const childrenContainer = document.createElement('div');
            childrenContainer.className = 'children-container';

            node.children.forEach(child => {
                const childElement = createNodeElement(child, depth + 1);
                childrenContainer.appendChild(childElement);
            });

            content.appendChild(childrenContainer);
        }

        // 切换显示/隐藏
        header.addEventListener('click', () => {
            const isExpanded = header.classList.contains('expanded');
            header.classList.toggle('expanded', !isExpanded);
            content.classList.toggle('visible', !isExpanded);
        });

        // 高亮可点击节点
        if (node.clickable) {
            header.classList.add('clickable');
        }

        // 添加深度缩进
        nodeElement.style.marginLeft = `${depth * 20}px`;

        nodeElement.appendChild(header);
        nodeElement.appendChild(content);

        return nodeElement;
    }

    // 截取屏幕
    function takeScreenshot() {
        fetch('/screenshot', {
            method: 'POST',
            timeout: 600000
        })
        .then(response => {
            return response.json()
        })
        .then(data => {
            screenshotImg.src = 'data:image/png;base64,' + data.screenshot;
            screenshotImg.style.display = 'block';
        })
        .catch(error => {
            console.log(error)
        });
    }

      // 截取屏幕
    function takeScreenshotNew() {
        fetch('/screenshotNew', {
            method: 'POST',
            timeout: 600000
        })
        .then(response => {
            return response.json()
        })
        .then(data => {
            screenshotImg.src = 'data:image/png;base64,' + data.screenshot;
            screenshotImg.style.display = 'block';
        })
        .catch(error => {
            console.log(error)
        });
    }

    // 截取特定节点
    function captureSpecificNode(nodeId, bounds) {
        showLoading(true);
        // 构建请求URL
        const params = new URLSearchParams({
            nodeId: nodeId,
            left: bounds.left,
            top: bounds.top,
            right: bounds.right,
            bottom: bounds.bottom
        });

        fetch(`/node/image?${params}`)
        .then(response => response.json())
        .then(data => {
            // 在新窗口显示截图
            const win = window.open('', '_blank');
            var html = "<img src='data:image/png;base64," + data.screenshot + "'>"
            win.document.write(html);
            win.document.close();
            statusDiv.textContent = 'Node screenshot captured';
            statusDiv.style.color = 'green';
        })
        .catch(error => {
            console.error('Error capturing node screenshot:', error);
            statusDiv.textContent = `Error: ${error.message}`;
            statusDiv.style.color = 'red';
        })
        .finally(() => showLoading(false));
    }

    function showLoading(show) {
        const loadingOverlay = document.querySelector('.loading-overlay');

        if (show) {
            if (!loadingOverlay) {
                const overlay = document.createElement('div');
                overlay.className = 'loading-overlay';
                overlay.innerHTML = '<div class="spinner"></div>';
                treeView.appendChild(overlay);
            }
        } else {
            if (loadingOverlay) {
                loadingOverlay.remove();
            }
        }
    }

     function clearTreeView() {
        treeView.innerHTML = '';
        allNodes = [];
        statusDiv.textContent = 'Cleared';
        statusDiv.style.color = '';
    }

    // 生成节点唯一标识符（简化版）
    function generateNodeId(node) {
        return `${node.className}-${node.bounds.left}-${node.bounds.top}-${node.bounds.right}-${node.bounds.bottom}`;
    }
});